﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Data.SqlClient;
using System.Data;

namespace SalaryChannel.Web
{
    [ServiceContract(Namespace = "http://salary.yangchao.ts.gs.chinamobile/")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ChannelViewService : ServiceAuthRoot
    {
        #region 渠道在线
        [OperationContract]
        public List<string> GetRegion(string CityCode)
        {
            // 在此处添加操作实现
            List<string> retList = new List<string>();
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.CM_Region
                                where q.CityCode == CityCode
                                select new
                                {
                                    County = string.Format("[{0}]{1}", q.CountyCode, q.CountyName)
                                };

                    if (query.Any())
                    {
                        foreach (var c in query)
                        {
                            retList.Add(c.County);
                        }
                    }
                }
            }
            catch
            {
                return null;
            }
            return retList;
        }

        /// <summary>
        /// 返回渠道列表
        /// </summary>
        /// <param name="CountyCode">=</param>
        /// <param name="ChannelID">=</param>
        /// <param name="ChannelName">like</param>
        /// <returns></returns>
        [OperationContract]
        public List<CM_Channel> GetChannelList(string CountyCode,
            string ChannelID, string ChannelName)
        {
            try
            {
                this.Authoricate();
                List<CM_Channel> cList = new List<CM_Channel>();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    if (!string.IsNullOrEmpty(ChannelName)
                         && !string.IsNullOrEmpty(ChannelID))
                    {
                        var query = from q in context.ChannelAccount
                                    where q.CountyCode == CountyCode && q.Id == ChannelID
                                    && q.ChannelName.Contains(ChannelName)
                                    select new { q.Id, q.ChannelName };
                        if (query.Any())
                        {
                            foreach (var c in query)
                            {
                                cList.Add(new CM_Channel { ChannelID = c.Id, ChannelName = c.ChannelName });
                            }
                        }
                    }
                    else if (string.IsNullOrEmpty(ChannelID))
                    {
                        var query = from q in context.ChannelAccount
                                    where q.CountyCode == CountyCode && q.ChannelName.Contains(ChannelName)
                                    select new { q.Id, q.ChannelName };
                        if (query.Any())
                        {
                            foreach (var c in query)
                            {
                                cList.Add(new CM_Channel { ChannelID = c.Id, ChannelName = c.ChannelName });
                            }
                        }
                    }
                    else if (string.IsNullOrEmpty(ChannelName))
                    {
                        var query = from q in context.ChannelAccount
                                    where q.CountyCode == CountyCode && q.Id == ChannelID
                                    select new { q.Id, q.ChannelName };
                        if (query.Any())
                        {
                            foreach (var c in query)
                            {
                                cList.Add(new CM_Channel { ChannelID = c.Id, ChannelName = c.ChannelName });
                            }
                        }
                    }
                    else
                    {
                        var query = from q in context.ChannelAccount
                                    where q.CountyCode == CountyCode 
                                    select new { q.Id, q.ChannelName };
                        if (query.Any())
                        {
                            foreach (var c in query)
                            {
                                cList.Add(new CM_Channel { ChannelID = c.Id, ChannelName = c.ChannelName });
                            }
                        }
                    }
                   
                }
                return cList;
            }
            catch(Exception ex)
            {
                LogManager.Write("GetChannelList," + ex.Message);
                return null;
            }
        }
        #endregion

        #region 渠道信息
        /// <summary>
        /// 获取渠道基本信息
        /// </summary>
        /// <param name="ChannelID"></param>
        /// <returns></returns>
        [OperationContract]
        public ChannelAccount GetChannelAccount(string ChannelID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.ChannelAccount
                                where q.Id == ChannelID
                                select q;
                    if (query.Any())
                    {
                        return query.First();
                    }
                    return new ChannelAccount() ;
                }
            }
            catch (Exception e)
            {
                LogManager.Write("GetChannelAccount:" + e.Message);
                return null;
            }
        }

        [OperationContract]
        public bool UpdateChannelAccount(string ChannelID,
            string Synopsis,
            string Chief,
            string EmployeeList,
            string Tel,
            string Address,
            string PostCode,
            string Bank,
            string BankAccountName,
            string BankAccount
        )
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.ChannelAccount
                                where q.Id == ChannelID
                                select q;
                    if (query.Any())
                    {
                        query.First().Synopsis = Synopsis;
                        query.First().Chief = Chief;
                        query.First().EmployeeList = EmployeeList;
                        query.First().Tel = Tel;
                        query.First().Address = Address;
                        query.First().Bank = Bank;
                        query.First().Bank_Account = BankAccount;
                        query.First().Bank_Account_Name = BankAccountName;
                        query.First().Postcode = PostCode;
                        context.SubmitChanges();
                        return true;

                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                LogManager.Write("UpdateChannelAccount：" + ex.Message);
                return false;
            }
        }

        #endregion

        #region 调研记录
        [OperationContract]
        public List<Survey> GetSurveyList(string ChannelID)
        {
            List<Survey> sList = new List<Survey>();

            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.SurveyHis
                                where q.ChannelID == ChannelID
                                select new
                                {
                                    q.ID,
                                    q.SurveyDate,
                                    q.SurveyChief,
                                    q.Subject,
                                    q.Score
                                };
                    if (query.Any())
                    {
                        foreach (var s in query)
                        {
                            sList.Add(new Survey
                            {
                                ID = s.ID,
                                Date = s.SurveyDate,
                                Chief = s.SurveyChief,
                                Subject = s.Subject,
                                Score = (short)s.Score
                            });
                        }
                    }
                }
                return sList;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取调研的详细信息
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [OperationContract]
        public SurveyHis GetSurveyDetailByID(int ID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.SurveyHis
                                where q.ID == ID
                                select q;
                    if (query.Any())
                    {
                        return query.First();
                    }
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 新增调研信息
        /// </summary>
        /// <param name="ChannelID"></param>
        /// <param name="Date"></param>
        /// <param name="Subject"></param>
        /// <param name="Chief"></param>
        /// <param name="Surveyer"></param>
        /// <param name="Score"></param>
        /// <param name="Content"></param>
        /// <param name="CreateID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool InsertSurveyDetail(
            string ChannelID,
            DateTime Date,
            string Subject,
            string Chief,
            string Surveyer,
            int Score,
            string Content,
            string CreateID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    context.SurveyHis.InsertOnSubmit(new SurveyHis
                    {
                        ChannelID = ChannelID,
                        SurveyDate = Date,
                        Subject = Subject,
                        SurveyChief = Chief,
                        Surveyer = Surveyer,
                        Score = (short?)Score,
                        Content = Content,
                        CreateID = CreateID,
                        CreateTime = DateTime.Now
                    });

                    context.SubmitChanges();
                    return true;
                }
            }
            catch (Exception e)
            {
                LogManager.Write("InsertSurveyDetail: " + e.Message + ", IP-" + HttpContext.Current.Request.UserHostAddress);
                return false;
            }

        }

        [OperationContract]
        public bool AttachSurveyContent(int ID, string AttachBody)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.SurveyHis
                                where q.ID == ID
                                select q;
                    if (query.Any())
                    {
                        query.First().Content += AttachBody;
                        context.SubmitChanges();
                        return true;
                    }
                    return false;

                }
            }
            catch (Exception ex)
            {
                LogManager.Write("AttachSurveyContent: " + ex.Message);
                return false;
            }
        }

        #endregion 

        #region 渠道风采
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="albumId"></param>
        /// <param name="ChannelID"></param>
        /// <param name="CreateID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool UploadPhoto(byte[] fileData, string photoID,
            string ChannelID)
        {           
            try
            {
                this.Authoricate();
                string ChannelDir = HttpContext.Current.Server.MapPath(@"./Image/" + ChannelID + "/");
                if (!Directory.Exists(ChannelDir))
                {
                    Directory.CreateDirectory(ChannelDir);
                }
                using (FileStream fs =
                      new FileStream(ChannelDir + "\\" + photoID + @".jpg", FileMode.Append, FileAccess.Write))
                {
                    fs.Write(fileData, 0, fileData.Length);
                    fs.Flush();
                }
                return true;

            }
            catch (Exception ex)
            {
                LogManager.Write("UploadFile: " + ex.Message);
                return false;
            }

           
        }

        /// <summary>
        /// 将图片信息写入DB
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="albumId"></param>
        /// <param name="ChannelID"></param>
        /// <param name="CreateID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool InsertPhoto( string title, string description, string albumId, string photoID,
            string ChannelID, string CreateID)
        {

            Photo photo = new Photo();
            photo.Id = photoID;
            photo.AccountId = ChannelID;
            photo.Title = title;
            photo.Description = description;
            photo.AlbumId = albumId;
            photo.CreateTime = DateTime.Now;
            photo.Score = 20;
            photo.CreateID = CreateID;

            try
            {
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    context.Photo.InsertOnSubmit(photo);
                    context.SubmitChanges();

                }
                return true;
            }
            catch (Exception e)
            {
                LogManager.Write("InsertPhoto: " + e.Message);
                return false;
            }

        }

        ///// <summary>
        ///// 查询渠道的相册列表
        ///// </summary>
        ///// <param name="ChannelID"></param>
        ///// <returns></returns>
        //[OperationContract]
        //public List<Album> GetAlbumListByChannelID(string ChannelID)
        //{
        //    try
        //    {
        //        this.Authoricate();
        //        using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
        //        {
        //            var query = from q in context.Album
        //                        where q.AccountId == ChannelID
        //                        select q;
        //            if (query.Any())
        //            {
        //                return query.ToList();

        //            }
        //            return new List<Album>();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogManager.Write(ex.Message);
        //        return null;
        //    }
        //}

        /// <summary>
        /// 查询渠道的相册列表和相册中图片数量
        /// </summary>
        /// <param name="ChannelID"></param>
        /// <returns></returns>
        [OperationContract]
        public List<VW_AlbumContains> GetAlbumsByChannelID(string ChannelID)
        {
            List<VW_AlbumContains> vList = new List<VW_AlbumContains>();
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.VW_AlbumContains
                                where q.ChannelID == ChannelID
                                select q;
                    if (!query.Any())
                    {
                        string temID = Guid.NewGuid().ToString();
                        context.Album.InsertOnSubmit(new Album
                        {
                            Id = temID,
                            AccountId = ChannelID,
                            Name = "默认相册",
                        });
                        context.SubmitChanges();
                        vList.Add(new VW_AlbumContains
                        {
                            ChannelID = ChannelID,
                            AlbumID = temID,
                            Name = "默认相册",
                            PhotoCount = 0
                        });
                    }
                    else
                    {
                        vList = query.ToList();
                    }
                }
                return vList;
            }
            catch (Exception e)
            {
                LogManager.Write("查询相册失败，" + e.Message);
                return null;
            }
        }

        /// <summary>
        /// 新建渠道相册
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Desc"></param>
        /// <param name="ChannelID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool NewAlbum(string Name, string Desc, string ChannelID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    context.Album.InsertOnSubmit(new Album
                    {
                        Id = Guid.NewGuid().ToString(),
                        AccountId = ChannelID,
                        Name = Name,
                        Description = Desc
                    });
                    context.SubmitChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Write("NewAlbum:" + ex.Message);
                     
                    return false;
            }
        }


        /// <summary>
        /// 更新相册信息
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Desc"></param>
        /// <param name="ChannelID"></param>
        /// <param name="AlbumID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool UpdateAlbum(string Name, string Desc, string AlbumID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.Album
                                where q.Id == AlbumID
                                select q;
                    if (query.Any())
                    {
                        query.First().Name = Name;
                        query.First().Description = Desc;
                        context.SubmitChanges();
                        return true;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("UpdateAlbum:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 删除相册及其中的照片
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool DeleteAlbum(string ID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.Album
                                where q.Id == ID
                                select q;
                    if (query.Any())
                    {
                        var photoList = from p in context.Photo
                                    where p.AlbumId == query.First().Id
                                    select p;
                        foreach (var ph in photoList)
                        {
                            DeletePhoto(ph.Id);
                        }
                        context.Album.DeleteOnSubmit(query.First());
                     
                        context.SubmitChanges();
                        return true;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("DeleteAlbum:" + ex.Message);
                return false;
            }

        }

        [OperationContract]
        public bool UpdatePhoto(string photoID,
            string title,
            string albumID,
            string description)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.Photo
                                where q.Id == photoID
                                select q;
                    if (query.Any())
                    {
                        query.First().Title = title;
                        query.First().AlbumId = albumID;
                        query.First().Description = description;
                        context.SubmitChanges();
                        return true;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("UpdatePhoto：" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 删除照片
        /// </summary>
        /// <param name="photoID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool DeletePhoto(string photoID)
        {
            this.Authoricate();
            using(DataClassesQueryDataContext context = new DataClassesQueryDataContext())
            {
                var query = from q in context.Photo
                            where q.Id == photoID
                            select q;
                if (query.Any())
                {
                    string photoPath = HttpContext.Current.Server.MapPath(@"./Image/"
                        + query.First().AccountId + @"/"+ photoID+@".jpg");

                    context.Photo.DeleteOnSubmit(query.First());

                    context.SubmitChanges();
                    try
                    {
                        File.Delete(photoPath);
                    }
                    catch 
                    {
                       
                    }
                    return true;
                }
                return false;
            }
        }
        /// <summary>
        /// 获取图片详细信息
        /// </summary>
        /// <param name="PhotoID"></param>
        /// <returns></returns>
        [OperationContract]
        public VW_PhotoInfor GetPhotoInfor(string PhotoID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.VW_PhotoInfor
                                where q.PhotoID == PhotoID
                                select q;
                    if (query.Any())
                    {
                        return query.First();
                    }
                    return new VW_PhotoInfor();
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("GetPhotoInfor: " + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public List<VW_PhotoComment> GetComments(string PhotoID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.VW_PhotoComment
                                where q.PhotoID == PhotoID
                                select q;
                    if (query.Any())
                    {
                        return query.ToList() ;
                    }
                    return new List<VW_PhotoComment>();
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("GetComments: " + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public bool InsertComment(string PhotoId, string CreateID, string Content)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    context.Comment.InsertOnSubmit(new Comment
                    {
                        PhotoId = PhotoId,
                        CreateId = CreateID,
                        Content = Content,
                        CreateTime = DateTime.Now
                    });
                    context.SubmitChanges();

                }
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Write("InsertComment: " + ex.Message);
                return false;
            }
        }

        [OperationContract]
        public List<VW_PhotoPath> GetPhotoPath(string ChannelID,
            string AlbumID, int StartIndex, int MaxLength)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    if (string.IsNullOrEmpty(AlbumID))
                    {
                        var query = from q in context.VW_PhotoPath
                                    where q.ChannelID == ChannelID
                                    orderby q.CreateTime 
                                    select q;
                        if (query.Any())
                        {
                            
                            return query.Skip(StartIndex).Take(MaxLength).ToList();
                        }
                        return new List<VW_PhotoPath>();
                    }
                    else
                    {
                        var query = from q in context.VW_PhotoPath
                                    where q.ChannelID == ChannelID
                                    where q.AlbumID == AlbumID
                                    orderby q.CreateTime 
                                    select q;
                        if (query.Any())    
                        {
                            
                            return query.Skip(StartIndex).Take(MaxLength).ToList();
                        }
                        return new List<VW_PhotoPath>();
                    }

                }
            }
            catch (Exception ex)
            {
                LogManager.Write("GetPhotoPath:" + ex.Message);
                return null;
            }
        }

        #endregion

        #region 业务统计

        [OperationContract]
        public List< SP_ChannelLostUsers_个结果> GetChannelLostUsers(string ChannelID)
        {
            try
            {
                this.Authoricate();
                List<SP_ChannelLostUsers_个结果> list = new List<SP_ChannelLostUsers_个结果>();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    context.CommandTimeout = 60000;
                    list.Add( context.SP_ChannelLostUsers(ChannelID).First());
                }
                return list;
            }
            catch (Exception ex)
            {

                LogManager.Write("SP_ChannelLostUsers_个结果，" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public List<SP_ChannelNewUsers_个结果> GetChannelNewUsers(string ChannelID)
        {
            try
            {
                this.Authoricate();
                List<SP_ChannelNewUsers_个结果> list = new List<SP_ChannelNewUsers_个结果>();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    context.CommandTimeout = 60000;
                    list.Add( context.SP_ChannelNewUsers(ChannelID).First());

                }
                return list;
            }
            catch (Exception ex)
            {

                LogManager.Write("SP_ChannelNewUsers个结果，" + ex.Message);
                return null;
            }
        }
        [OperationContract]
        public List<UserFeeLevel> GetChannelUserFeeLevel(string ChannelID)
        {
            string sqlStr = System.Configuration.ConfigurationManager.ConnectionStrings["SalaryQueryConnectionString"].ConnectionString;
            try
            {
                this.Authoricate();
                List<UserFeeLevel> uList = new List<UserFeeLevel>();
                using (SqlConnection con = new SqlConnection(sqlStr))
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandTimeout = 150000;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_ChannelUserFeeLevel";
                    cmd.Parameters.Add(new SqlParameter("@ChannelID", ChannelID));
                    DataTable dt = new DataTable();
                    SqlDataAdapter ads = new SqlDataAdapter(cmd);
                    ads.Fill(dt);

                    UserFeeLevel u = new UserFeeLevel();
                    int count = 0;
                    foreach (DataRow row in dt.Rows)
                    {
                        switch ((int)(row[0]))
                        {
                            case 0: u.Fee0 = (int)(row[1]);
                                break;
                            case 1: u.Fee1 = (int)(row[1]);
                                break;
                            case 2: u.Fee2 = (int)(row[1]);
                                break;
                            case 3: u.Fee3 = (int)(row[1]);
                                break;
                            case 5: u.Fee5 = (int)(row[1]);
                                break;
                            case 8: u.Fee8 = (int)(row[1]);
                                break;
                            case 12: u.Fee12 = (int)(row[1]);
                                break;
                            case 13: u.Fee12Up = (int)(row[1]);
                                break;
                            default: break;
                        }
                        count += (int)(row[1]);
                    }
                    u.FeeAll = count;
                    uList.Add(u);

                   return uList;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("GetChannelUserFeeLevel:" + ex.Message);
                return null;
            }
        }

        #endregion


        [OperationContract]
        public string test(byte[] data)
        {
            return data.Length.ToString();
        }

    }

    
    public class UserFeeLevel
    {
        public int Fee0 {get;set;}
        public int Fee1 {get;set;}
        public int Fee2 {get;set;}
        public int Fee3 {get;set;}
        public int Fee5 {get;set;}
        public int Fee8 {get;set;}
        public int Fee12 {get;set;}
        public int Fee12Up {get;set;}
        public int FeeAll {get;set;}
    }


    public class Survey
    {
        public int ID {get;set;}
        public DateTime Date{get;set;}
        public string Chief {get;set;}
        public string Subject {get;set;}
        public short Score {get;set;}
    }

    public class CM_Channel
    {
        public string ChannelID { get; set; }
        public string ChannelName { get; set; }
    }
}
